package com.qclix.inv.textui;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.HashMap;
import java.util.Map;

/**
 * Application entry point
 */
public class Main implements FlowHandler {
    private Map<HANDLER, ActionHandler> handlers;
    private HANDLER nextHandler;

    private ApplicationContext context;

    public static void main(String[] arguments) throws Exception {
        Main main = new Main();
        main.start();
    }

    public Main() {
        context = new ClassPathXmlApplicationContext("spring-context-core.xml");
        handlers = new HashMap<HANDLER, ActionHandler>();
        registerHandlers();
    }

    private void registerHandlers() {
        handlers.put(HANDLER.topMenu, (ActionHandler) context.getBean("ui.handler.topMenu"));
        handlers.put(HANDLER.exit, (ActionHandler) context.getBean("ui.handler.exit"));
        handlers.put(HANDLER.newClient, (ActionHandler) context.getBean("ui.handler.newClient"));
        handlers.put(HANDLER.newInvoice, (ActionHandler) context.getBean("ui.handler.newInvoice"));
        handlers.put(HANDLER.pdfLastInvoice, (ActionHandler) context.getBean("ui.handler.pdfLastInvoice"));

        for(ActionHandler handler: handlers.values()) {
            handler.setFlowHandler(this);
        }
    }

    public void start() throws Exception {
        nextHandler = HANDLER.topMenu;
        while(true) {
            handlers.get(nextHandler).handle();
        }
    }

    public void setNexFlow(HANDLER handler) {
        this.nextHandler = handler;
    }
}
